import { Get, Inject, Param } from '@midwayjs/core';
import {
  BaseController,
  CoolController,
  CoolTag,
  CoolUrlTag,
  TagTypes,
} from '@cool-midway/core';
import { GoodsTypeService } from '../../../goods/service/type';
import { GoodsInfoService } from '../../../goods/service/info';
import { Context } from '@midwayjs/koa';
import { InfoService } from '../../../info/service/info';

/**
 * 商城首页
 */
@CoolUrlTag({
  key: TagTypes.IGNORE_TOKEN,
  value: ['index', 'detail'],
})
@CoolController()
export class ShopHomeController extends BaseController {
  @Inject()
  goodsTypeService: GoodsTypeService;

  @Inject()
  goodsInfoService: GoodsInfoService;

  @Inject()
  infoService: InfoService;

  @Inject()
  ctx: Context;

  /**
   * 首页数据
   */
  @Get('/')
  @CoolTag(TagTypes.IGNORE_TOKEN)
  async index() {
    try {
      // 获取分类
      const categories = await this.goodsTypeService.list(
        {
          status: 1,
          orderBy: {
            sortNum: 'DESC',
          },
        },
        {}
      );

      // 获取轮播图
      // const banners = await this.infoService.listByEnabled();
      const banners = [
        {
          id: 1,
          title: '专业医疗设备',
          description: '引进全球领先的医疗设备，为您提供最优质的医疗服务',
          pic: 'https://img.freepik.com/free-photo/medical-banner-with-doctor-working-hospital_23-2149611193.jpg',
          url: '/category/equipment',
          enabled: 1,
        },
        {
          id: 2,
          title: '品质保障药品',
          description: '严格把控药品质量，守护您的健康',
          pic: 'https://img.freepik.com/free-photo/pharmacist-holding-medicine-box-capsule-pack-pharmacy-drugstore_43157-8200.jpg',
          url: '/category/medicine',
          enabled: 1,
        },
        {
          id: 3,
          title: '专业医疗团队',
          description: '资深医师团队，提供专业诊疗服务',
          pic: 'https://img.freepik.com/free-photo/team-young-specialist-doctors-standing-corridor-hospital_146671-18443.jpg',
          url: '/category/team',
          enabled: 1,
        },
        {
          id: 4,
          title: '智慧医疗科技',
          description: '运用先进科技，打造智慧医疗服务平台',
          pic: 'https://img.freepik.com/free-photo/medical-technology-researcher-working-laboratory_23-2150516034.jpg',
          url: '/category/tech',
          enabled: 1,
        },
        {
          id: 5,
          title: '全方位健康服务',
          description: '预防、诊断、治疗、康复一站式服务',
          pic: 'https://img.freepik.com/free-photo/doctor-with-stethoscope-hands-hospital-background_1423-1.jpg',
          url: '/category/service',
          enabled: 1,
        },
      ];
      // 获取菜单
      const menus = [
        {
          id: 1,
          name: '新品上市',
          icon: 'https://img.icons8.com/plasticine/100/new.png',
          url: '/new',
        },
        {
          id: 2,
          name: '热卖商品',
          icon: 'https://img.icons8.com/plasticine/100/fire-element.png',
          url: '/hot',
        },
        {
          id: 3,
          name: '特价促销',
          icon: 'https://img.icons8.com/plasticine/100/sale.png',
          url: '/sale',
        },
        {
          id: 4,
          name: '品牌专区',
          icon: 'https://img.icons8.com/plasticine/100/shop.png',
          url: '/brand',
        },
        {
          id: 5,
          name: '领券中心',
          icon: 'https://img.icons8.com/plasticine/100/ticket.png',
          url: '/coupon',
        },
      ];

      // 获取热门商品
      const hotGoods = await this.goodsInfoService.getGoodsFromFixture({
        source: 'source-3',
        num: 10,
        attribute: 3,
      });

      // 获取推荐商品
      const recommendGoods = await this.goodsInfoService.getGoodsFromFixture({
        source: 'source-3',
        num: 10,
        attribute: 3,
      });

      // 渲染视图
      return await this.ctx.render('shop/view/index', {
        title: '商城首页',
        categories,
        banners,
        menus,
        hotProducts: hotGoods,
        bannerHeight: 400,
        recommendProducts: recommendGoods,
      });
    } catch (error) {
      console.error('获取首页数据失败:', error);
      return this.fail('获取首页数据失败');
    }
  }

  /**
   * 商品详情页
   */
  @Get('/detail/:id')
  @CoolTag(TagTypes.IGNORE_TOKEN)
  async detail(@Param('id') id: string) {
    try {
      // 获取商品详情
      const goodsInfo = await this.goodsInfoService.info(parseInt(id));

      // 获取分类
      const categories = await this.goodsTypeService.list(
        {
          status: 1,
          orderBy: {
            sortNum: 'DESC',
          },
        },
        {}
      );

      const parentCategories = categories.filter(cat => !cat.parentId);
      parentCategories.forEach((category, index) => {
        const children = categories.filter(
          child => child.parentId === category.id
        );
        category.children = children;
      });
      if (!goodsInfo) {
        return this.fail('商品不存在');
      }

      // 补充商品图片数据
      const goodsData = {
        ...goodsInfo,
        mainPic: goodsInfo.mainPic || '/images/default-product.jpg',
        pics: goodsInfo.pics || [
          '/images/product-1.jpg',
          '/images/product-2.jpg',
          '/images/product-3.jpg',
          '/images/product-4.jpg',
        ],
        price: goodsInfo.price || 0,
        originalPrice: goodsInfo.originalPrice,
        description: goodsInfo.description || '暂无描述',
        brand: goodsInfo.brand || '优品汇',
      };

      // 获取相关推荐商品
      const recommendGoods = await this.goodsInfoService.getGoodsFromFixture({
        source: 'source-3',
        num: 8,
        attribute: 3,
      });

      // 模拟商品规格数据
      const specs = {
        colors: [
          { id: 1, name: '黑色', image: 'black.jpg' },
          { id: 2, name: '白色', image: 'white.jpg' },
          { id: 3, name: '灰色', image: 'gray.jpg' },
          { id: 4, name: '蓝色', image: 'blue.jpg' },
          { id: 5, name: '红色', image: 'red.jpg' },
        ],
        sizes: [
          { id: 1, name: '160/84A' },
          { id: 2, name: '165/88A' },
          { id: 3, name: '170/92A' },
          { id: 4, name: '175/96A' },
          { id: 5, name: '185/104A' },
        ],
      };

      // 模拟优惠券数据
      const coupons = [
        {
          id: 1,
          amount: 50,
          threshold: 300,
          name: '全品类通用券',
          platform: '全平台',
          validUntil: '2024-12-31',
        },
        {
          id: 2,
          amount: 30,
          threshold: 200,
          name: '全品类通用券',
          platform: '全平台',
          validUntil: '2024-12-31',
        },
        {
          id: 3,
          amount: 10,
          threshold: 100,
          name: '全品类通用券',
          platform: '全平台',
          validUntil: '2024-12-31',
        },
      ];

      // 模拟商品详细参数
      const params = {
        basicInfo: {
          衣长: '常规',
          领型: '可脱卸帽',
          款式细节: '多口袋',
          充绒量: '100g(含)-150g(不含)',
          含绒量: '90%',
          材质成分: '聚酯纤维100%',
          品牌: goodsData.brand,
          填充物: '白鹅绒',
          上市年份: '2024年春季',
        },
        serviceInfo: {
          退货说明: [
            '30天无忧退货',
            '48小时快速退款',
            '满88元免邮费',
            '多仓直发',
            '品质保障',
          ],
          运费说明:
            '单笔订单金额(不含运费)满88元免邮费；不满88元，每单收取10元运费。',
          发货说明: '默认使用顺丰快递发货(个别商品使用其他快递）',
          退货流程: [
            '确认收货-申请退货-客服审核通过',
            '用户寄回商品-仓库签收验货',
            '退款审核-退款完成',
          ],
        },
      };

      // 渲染商品详情页
      return await this.ctx.render('shop/view/detail', {
        title: goodsData.name,
        goods: goodsData,
        specs,
        coupons,
        params,
        categories: parentCategories,
        recommendGoods: recommendGoods.map(item => ({
          ...item,
          mainPic: item.mainPic || '/images/default-product.jpg',
          description: item.description || '暂无描述',
          price: item.price || 0,
        })),
        breadcrumb: [
          { name: '首页', url: '/' },
          { name: '服装', url: '/category/clothing' },
          { name: '外衣', url: '/category/clothing/outerwear' },
          { name: goodsData.name, url: '' },
        ],
      });
    } catch (error) {
      console.error('获取商品详情失败:', error);
      return this.fail('获取商品详情失败');
    }
  }
}
